package wechat

import (
	"encoding/json"
	"fmt"
	"github.com/silenceper/wechat/v2/util"
	"xialou_platform/app/errorx"
)

const (
	getBankByNumUrl = "https://api.weixin.qq.com/shop/funds/getbankbynum"
)

type GetBankByNumReq struct {
	AccountNumber string `json:"account_number"`
}

type GetBankByNumResp struct {
	Data []struct {
		BankCode    string `json:"bank_code"`
		BankId      int    `json:"bank_id"`
		BankName    string `json:"bank_name"`
		NeedBranch  bool   `json:"need_branch"`
		AccountBank string `json:"account_bank"`
	} `json:"data"`
	TotalCount int    `json:"total_count"`
	Errmsg     string `json:"errmsg"`
	Errcode    int    `json:"errcode"`
}

// GetBankByNum 根据卡号查银行信息
func GetBankByNum(accessToken, bankNumber string) (resp GetBankByNumResp, err error) {

	uri := fmt.Sprintf("%s?access_token=%s", getBankByNumUrl, accessToken)

	req := GetBankByNumReq{
		AccountNumber: bankNumber,
	}
	bytes, err := json.Marshal(req)
	if err != nil {
		return GetBankByNumResp{}, err
	}
	reqStr := string(bytes)

	response, err := util.HTTPPost(uri, reqStr)
	if err != nil {
		return
	}

	err = json.Unmarshal(response, &resp)
	if err != nil {
		return GetBankByNumResp{}, fmt.Errorf("json Unmarshal Error, err=%v", err)
	}

	if resp.Errcode == 9710001 {
		return GetBankByNumResp{}, errorx.NewDefaultError("银行卡号有误")
	}

	return
}
